package com.zx._07_数据库.测试数据;

import com.google.common.collect.Lists;
import com.zx._07_数据库.jdbc.JDBC;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SaveSc {

    /**
     * 完成的随机生成，可能部分学生，部分班级没有数据
     */
    public static void save() {
        log.info("save sc begin");
        int thread = Config.SAVE_THREAD;
        ExecutorService pool = Executors.newFixedThreadPool(thread);

        int scCount = Config.SC_COUNT;

        int step = scCount % thread == 0 ? scCount / thread : scCount / (thread + 1);

        int begin = 0;
        int end = begin + step;

        List<Future<Boolean>> res = Lists.newArrayList();
        for (int j = 0; j < Config.SAVE_THREAD; j++) {
            final int beginFinal = begin;
            final int endFinal = end;
            Future<Boolean> submit = pool.submit(() -> {
                String sql = "INSERT INTO t_sc (id, s_id, c_id, score) VALUES(?,?,?,?)";
                Random random = new Random();

                Connection connection = JDBC.getConnection();
                PreparedStatement ps = null;
                try {
                    ps = connection.prepareStatement(sql);
                    int counter = 0;
                    for (int i = beginFinal; i < endFinal; i++) {
                        ps.setInt(1, i + 1);
                        ps.setInt(2, random.nextInt(Config.STUDENT_COUNT));
                        ps.setInt(3, random.nextInt(Config.COURSE_NAMES.length));
                        ps.setInt(4, random.nextInt(100));
                        ps.addBatch();
                        if (counter >= 1000) {
                            ps.executeBatch();
                            counter = 0;
                        }
                        counter++;
                    }
                    ps.executeBatch();
                    log.info("save sc thread {} done", Thread.currentThread().getName());
                } catch (Exception e) {
                    log.error("save sc error", e);
                } finally {
                    JDBC.release(connection, ps, null);
                }
                return true;
            });

            res.add(submit);
            scCount -= step;
            begin = end;
            end = end + Math.min(step, scCount);
        }

        for (Future<Boolean> re : res) {
            try {
                re.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        pool.shutdown();
        log.info("save sc finsh");
    }
}
